﻿using System.Reflection;
using Newtonsoft.Json;
using TenantSecurityProvider.Models;

namespace TenantSecurityProvider.Utils;

/// <summary>
/// 配置工具类
/// </summary>
public abstract class ConfigUtils
{
    /// <summary>
    /// 配置对象
    /// </summary>
    private static Config _config;

    /// <summary>
    /// 配置文件路径
    /// </summary>
    private static string _configFilePath;

    /// <summary>
    /// 配置文件路径
    /// </summary>
    private static string ConfigFilePath
    {
        get
        {
            /*if (_configFilePath != null)
            {
                return _configFilePath;
            }*/

            var assemblyLocation = Assembly.GetExecutingAssembly().Location;

            if (AppDomain.CurrentDomain.ShadowCopyFiles)
            {
                var uri = new Uri(Assembly.GetExecutingAssembly().Location);
                assemblyLocation = uri.LocalPath;
            }

            var dir = Path.GetDirectoryName(assemblyLocation);

            _configFilePath = Path.Combine(dir!, "config.json");

            return _configFilePath;
        }
    }

    /// <summary>
    /// 获取配置
    /// </summary>
    /// <param name="forceReadFromDisk">是否强制从磁盘读取</param>
    /// <returns></returns>
    public static Config GetConfig(bool forceReadFromDisk = false)
    {
        if (forceReadFromDisk || _config == null)
        {
            _config = JsonConvert.DeserializeObject<Config>(File.ReadAllText(ConfigFilePath));
        }

        return _config;
    }

    /// <summary>
    /// 更新配置
    /// </summary>
    /// <param name="config"></param>
    public static void SetConfig(Config config)
    {
        MakeFileNotReadOnly();
        File.WriteAllText(ConfigFilePath, JsonConvert.SerializeObject(config));
        _config = config;

    }

    /// <summary>
    /// 处理文件只读属性
    /// </summary>
    private static void MakeFileNotReadOnly()
    {
        if (!File.Exists(_configFilePath))
        {
            return;
        }

        if ((File.GetAttributes(_configFilePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
        {
            File.SetAttributes(_configFilePath, File.GetAttributes(_configFilePath) & ~FileAttributes.ReadOnly);
        }
    }
}
